package db;

import ming.User;

import java.sql.*;

public class Database {
    Connection conn = null;

    public Database() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");//注册驱动
        this.conn = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "123456");
        System.out.println(conn);
    }

    public void showConnect() {
        if (conn == null) {
            System.out.println("数据库连接失败");
        } else {
            System.out.println("数据库连接成功");
        }
    }

    public void close() throws SQLException {
        conn.close();
    }

    //在表里查询数据
    public User getuser(String  name) throws SQLException {
        PreparedStatement prep = conn.prepareStatement("select * from web_framework.userinfor where username=?");
        prep.setString(1, name);
        prep.execute();
        ResultSet resultSet = prep.executeQuery();
        if (resultSet.next()) {
            String myname = resultSet.getString("username");
            String mypwd = resultSet.getString("userpassword");
            return new User(  myname, mypwd);
        }
        return null;
    }

    public User login(String name, String pwd) throws SQLException {
        PreparedStatement prep = conn.prepareStatement("select web_framework.userinfor.userpassword from web_framework.userinfor where username=?");
        prep.setString(1,name);//为问号赋值
        prep.execute();
        ResultSet resultSet = prep.executeQuery();
        if (resultSet.next()) {
            String mypwd = resultSet.getString("userpassword");
            //mypwd是输入的，pwd是数据库的
            if (pwd.equals(mypwd)) {
                return getuser(name);
            }
            else
                return null;
        }
        else
            return null;
    }
}

